/**
 * 构造树型结构数据
 * @param {*} datas 数据源
 * @param {*} code id字段 默认 'code'
 * @param {*} parent_code 父节点字段 默认 'parent_code'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export function handleTree( datas:object, code:string, parent_code?:string, children?:Object) {
	let config = {
		code: orData(code , 'code'),
		parent_code: orData(parent_code , 'parent_code'),
		childrenList: orData(children , 'children')
	};

	var childrenListMap = {};
	var nodeIds = {};
	var tree = [];

	for (let d of datas) {
		let parent_codes = d[config.parent_code];
		if (childrenListMap[parent_codes] == null) {
			childrenListMap[parent_codes] = [];
		}
		nodeIds[d[config.code]] = d;
		childrenListMap[parent_codes].push(d);
	}

	for (let d of datas) {
		let parent_codes = d[config.parent_code];
		if (nodeIds[parent_codes] == null) {
			tree.push(d);
		}
	}

	for (let t of tree) {
		adaptToChildrenList(t);
	}

	function adaptToChildrenList(o) {
		if (childrenListMap[o[config.code]] !== null) {
			o[config.childrenList] = childrenListMap[o[config.code]];
		}
		if (o[config.childrenList]) {
			for (let c of o[config.childrenList]) {
				adaptToChildrenList(c);
			}
		}
	}
	return tree;
}

// 或操作
function orData(data1,data2){
	return data1 || data2
}